package com.es.queue;

import javax.sql.rowset.FilteredRowSet;

/**
 * @author 二十
 */
public class LoopQueue<E> extends AbstractQueue<E> {

    private E[] data;

    private int front, tail, size;

    public LoopQueue() {
        data = (E[]) new Object[10];
    }

    public LoopQueue(int capacity) {
        data = (E[]) new Object[capacity + 1];
    }

    @Override
    public void enqueue(E e) {

        //如果达到扩容阈值，那就扩容
        if ((tail + 1) % data.length == front) {
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail + 1) % data.length;
        size++;
    }

    private void resize(int capacity) {

        E[] arr = (E[]) new Object[capacity + 1];
        for (int i = 0; i < size; i++) {
            arr[i] = data[(front + i) % data.length];
        }
        data = arr;
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue empty!");
        }
        E ret = data[front];

        data[front] = null;

        front = (front + 1) % data.length;
        size--;

        //判断是否要缩容、
        if (size == getCapacity() / 4 && getCapacity() / 2 != 0) {
            resize(getCapacity() / 2);
        }
        return ret;
    }

    private int getCapacity() {
        return data.length - 1;
    }

    @Override
    public E getFront() {
        if (isEmpty()) {
            throw new IllegalArgumentException("Queue empty!");
        }
        return data[front];
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return front == tail;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Queue:Front <-[");
        for (int i = front; i < tail; i = (i + 1) % data.length) {
            sb.append(data[i]);
            if ((i + 1) % data.length != tail) {
                sb.append(",");
            }
        }
        sb.append("]<-Tail");
        return sb.toString();
    }
}
